
#include "StdAfx.h"
#include "AutoMakeRoom.h"
#include "User.h"
#include "LobbyService.h"
#include "Room.h"
#include "RoomManager.h"
#include <LogService.h>

AutoMakeRoom::AutoMakeRoom(){	
	reset();
}

AutoMakeRoom::~AutoMakeRoom(){
	reset();
}

void AutoMakeRoom::reset(){
	memset( data_, DEF_MAX_DATA_SIZE, 0 );
	owner_ = 0;
	users_.clear();	
}

int AutoMakeRoom::register_owner( User* user, char* data, int size ){
	if(! user )
		return -1;

	if(! data )
		return -1;

	if(! size )
		return -1;

	owner_ = user;
	memcpy( data_, data, size );
	data_size_ = size;

	return 0;
}

int AutoMakeRoom::register_member( User* user ){
	users_.push_back( user );

	return 0;
}

int AutoMakeRoom::make(){
	if(! owner_ )
		return -1;

	if( (! owner_ ) && (! users_.size() ) )
		return -1;

	Room* room = 0;
	RoomCreate* room_create = LobbyService::Instance()->getRoomCreate();
	RoomEnter* room_enter = LobbyService::Instance()->getRoomEnter();
	RoomManager* rooms = LobbyService::Instance()->getRoomManager();
	
	int result = room_create->create( data_, owner_, &room );
	if( result ){		
		LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__) );
		reset();		
		return result;
	}

	if(! room )		
		return -1;	

	result = room_enter->enter( room->getIdent(), owner_, room, 0 );
	if( result ){
		LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__) );
		reset();		
		return result;
	}
	
	User* user = 0;
	for( size_t i = 0 ; i < users_.size() ; i++ ){
		user = users_[ i ];

		result = room_enter->enter( room->getIdent(), user, room, 0 );
		if( result ){
			LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__) );
			reset();			
			return result;
		}
	}
	
	reset();
	return 0;
}
